﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;

namespace SecurityAdmin.Web.Microsoft
{
    public class MembershipCreationHelper
    {
        private string GenerateSalt()
        {
            byte[] buf = new byte[16];
            (new RNGCryptoServiceProvider()).GetBytes(buf);
            return Convert.ToBase64String(buf);
        }

        private string EncodePassword(string pass, int passwordFormat, string salt)
        {
            if (passwordFormat == 0) // MembershipPasswordFormat.Clear
                return pass;

            byte[] bIn = Encoding.Unicode.GetBytes(pass);
            byte[] bSalt = Convert.FromBase64String(salt);
            byte[] bAll = new byte[bSalt.Length + bIn.Length];
            byte[] bRet = null;

            Buffer.BlockCopy(bSalt, 0, bAll, 0, bSalt.Length);
            Buffer.BlockCopy(bIn, 0, bAll, bSalt.Length, bIn.Length);
            if (passwordFormat == 1)
            {
                // MembershipPasswordFormat.Hashed

                //When I moved from .NET 3.5 to .NET 4.0, they changed default alg.
                /*http://stackoverflow.com/questions/2823772/bad-crypto-error-in-net-4-0 */
                //<machineKey validation="SHA1" />
                //HashAlgorithm s = HashAlgorithm.Create( Membership.HashAlgorithmType );
                HashAlgorithm s = HashAlgorithm.Create("SHA1");
                bRet = s.ComputeHash(bAll);
            }
            else
            {
                Debug.Assert(true);
                //TODO
                //bRet = EncryptPassword(bAll);
            }

            return Convert.ToBase64String(bRet);
        }


    }
}